package com.quotientintelligence.webdev.caftrak;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.List;

import javax.servlet.http.*;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

import javax.jdo.PersistenceManager;
import com.quotientintelligence.PMF;

import com.quotientintelligence.caftrak.shared.CoffeeShop;
import com.quotientintelligence.caftrak.shared.ConsumptionEvent;
import com.quotientintelligence.caftrak.shared.ProductFactory;
import com.quotientintelligence.caftrak.shared.Substance;



@SuppressWarnings("serial")
public class CafTrakServlet extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		UserService us = UserServiceFactory.getUserService();
		User u = us.getCurrentUser();
		
		PrintWriter pr = resp.getWriter();
		if(u != null) {
		resp.setContentType("text/html");
		pr.println("Hello, " + u.getNickname());
		pr.println("<a href=\"" + us.createLogoutURL(req.getRequestURI()) +"\">Sign Out</a>");
		}else {
			resp.sendRedirect(us.createLoginURL(req.getRequestURI()));
		}
	
		pr.println("<br />");
		ProductFactory myLocalStarbucks = new CoffeeShop();
		Substance sb = myLocalStarbucks.getAFix("Starbucks", 10);

		pr.println(sb.Name + " is a " + sb.get_substanceType() + " with " + sb.get_substanceType().name());
		
		pr.println("<br />");

		Date date = new Date();
		ConsumptionEvent dr = new ConsumptionEvent(u,sb,date);

		PersistenceManager pm = PMF.get().getPersistenceManager();
		try
		{
			pm.makePersistent(dr);
		}
		catch (Exception e)
		{
			pr.println(e.getMessage());
		}
		try
		{
		
		    String query = "select from " + ConsumptionEvent.class.getName();
		    @SuppressWarnings("unchecked")
			List<ConsumptionEvent> drinks = (List<ConsumptionEvent>) pm.newQuery(query).execute();
		    if (drinks.isEmpty()) {
		    	pr.println("<p>You have not consumed any drinks!</p>");
		    } else {
		        for (ConsumptionEvent d : drinks) {
		            if (d.getUser() == null) {
				    	pr.println("<p>An anonymous person chugged:</p>");
		            } else {
				    	pr.println("<p>" + d.getUser().getNickname() + " drank:</p>");
		            }
	
		            if(d.getSubstance() != null)
			            pr.println(
			            		"<blockquote>" + d.getSubstance().Name + " a " + 
			            		d.getSubstance().Name + " on " 
			            		+ d.getDate() + "</blockquote>");
		        }
		    }
		}
		finally
		{
			pm.close();
		}

	}
}

